package com.core.life.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.core.life.dao.IAccountingRelationsDao;
import com.core.life.dao.IConsumeRecordDao;
import com.core.life.service.IConsumeCountService;
import com.core.life.vo.ConsumeCountVo;
import com.core.sys.dao.IUserDao;
import com.core.sys.entity.UserEntity;
import com.core.sys.service.IUserService;
import com.utils.date.DateUtil;

@Service
public class ConsumeCountServiceImpl implements IConsumeCountService{

	@Resource
	private IConsumeRecordDao consumeRecordDao;
	@Resource
	private IUserDao userDao;
	@Resource
    private IAccountingRelationsDao accountingRelationsDao;
	@Resource
	private IUserService userService;
	
	@Override
	public List<ConsumeCountVo> getConsumeCountList(String strDate, String consumeUserIds) {
		List<UserEntity> userList = null;
        if(StringUtils.isNotBlank(consumeUserIds)){
            String[] userIds = consumeUserIds.split(",");
            Long[] consumeUserIdArray = new Long[userIds.length];
            for (int i = 0; i < userIds.length; i++) {
                consumeUserIdArray[i] = Long.parseLong(userIds[i]);
            }
            //升序
            Arrays.sort(consumeUserIdArray);
            userList = userDao.selectByUserIds(consumeUserIdArray);
        }else{
            userList = userDao.findByParam("deleteFlag", false);
        }
        
		Date countDate = null;
		if(StringUtils.isNotBlank(strDate)){
			//格式：yyyy-MM
			//添加月份的第一天，时间格式：yyyy-MM-dd
			strDate = strDate + "-01";
			countDate = DateUtil.format(strDate, "yyyy-MM-dd");
		}else{
			countDate = new Date();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(countDate);
		return this.getConsumeCountList(userList, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1);
	}
	
	private List<ConsumeCountVo> getConsumeCountList(List<UserEntity> userList, int year, int month) {
		if(CollectionUtils.isNotEmpty(userList)){
		    List<Long> userIdList = new ArrayList<Long>(userList.size());
		    for (UserEntity userEntity : userList) {
                userIdList.add(userEntity.getId());
            }
		    List<Long> consumeRecordIdsList = consumeRecordDao.selectIdsByYearAndMonthAndConsumeUserIds(year, month, StringUtils.join(userIdList, ","));
			if(CollectionUtils.isNotEmpty(consumeRecordIdsList)){
			    List<Object[]> list = accountingRelationsDao.selectSumByConsumeRecordIds(consumeRecordIdsList);
                Map<Long,Double> userTotalPaidMap = new HashMap<Long,Double>(list.size());
                Map<Long,Double> userTotalConsumeMap = new HashMap<Long,Double>(list.size());
                for (Object[] objects : list) {
                    Long sourceUserId = Long.parseLong(objects[0].toString());
                    Long targetUserId = Long.parseLong(objects[1].toString());
                    Double payMoney = (Double) objects[2];
                    Double incomeMoney = userTotalPaidMap.get(targetUserId);
                    if(null == incomeMoney)
                        incomeMoney = 0.0;
                    incomeMoney += payMoney;
                    userTotalPaidMap.put(targetUserId, incomeMoney);
                    
                    Double expendMoney = userTotalConsumeMap.get(sourceUserId);
                    if(null == expendMoney)
                        expendMoney = 0.0;
                    expendMoney += payMoney;
                    userTotalConsumeMap.put(sourceUserId, expendMoney);
                }
//                DecimalFormat df   = new DecimalFormat("######0.00");  
                List<ConsumeCountVo> consumeCountList = new ArrayList<ConsumeCountVo>(list.size());
                ConsumeCountVo consumeCount = null;
                for (UserEntity user : userList) {
                    consumeCount = new ConsumeCountVo();
                    consumeCount.setUserName(user.getUserName());
                    consumeCount.setCountDate(year + "-" + month);
                    
                    double totalPaid = 0.0;
                    if (null != userTotalPaidMap.get(user.getId()))
                        totalPaid = new BigDecimal(userTotalPaidMap.get(user.getId())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    consumeCount.setTotalPaid(totalPaid);
                    
                    double totalConsume = 0.0;
                    if (null != userTotalConsumeMap.get(user.getId()))
                        totalConsume = new BigDecimal(userTotalConsumeMap.get(user.getId())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    consumeCount.setTotalConsume(totalConsume);
                    
                    double income =  totalPaid - totalConsume;
                    if (income > 0) {
                        consumeCount.setTotaliIncome(income);
                        consumeCount.setTotalExpenditure(0);
                    } else {
                        consumeCount.setTotaliIncome(0);
                        consumeCount.setTotalExpenditure(-income);
                    }
                    consumeCountList.add(consumeCount);
                }
				return consumeCountList;
			}
		}
		return null;
	}

}
